<!-- 申请科室统计列表 -->
<template>
  <div class="ky-container">
    <el-card shadow="hover" class="ky-card ky-card-xs ky-card-hdbg">
      <el-form
        ref="ruleForm"
        :model="formData"
        :inline="true"
        class="ky-form-inline ky-form-inline-sm"
        :rules="rules"
        label-width="84px"
      >
        <el-form-item label="医院名称:" prop="hospitalCode">
          <el-select
            size="small"
            class="param-type_input"
            v-model="formData.hospitalCode"
            placeholder="请选择"
            filterable
            @change="handleChange('hospital')"
          >
            <el-option
              v-for="(item,index) in mx_hospitalList"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="影像区域:">
          <el-select
            size="small"
            class="param-type_input"
            v-model="formData.depArea"
            multiple
            placeholder="请选择"
            clearable
            @change="handleChange('depArea')"
          >
            <el-option
              v-for="(item,index) in depAreaOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查部门:">
          <el-select
            size="small"
            class="param-type_input"
            v-model="formData.dep"
            multiple
            placeholder="请选择"
            clearable
            @change="handleChange('dep')"
          >
            <el-option
              v-for="(item,index) in scheduledDepOptions"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请科室" label-width="82px" prop="department">
          <el-select
            size="small"
            class="param-type_input"
            v-model="formData.department"
            placeholder="请选择"
            clearable
            multiple
          >
            <el-option v-for="item in departmentOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间:" prop="timeRange">
          <el-date-picker
            v-model="formData.timeRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <!-- <el-button class="m-l-0 click-button" size="small" @click="resetParam" plain>重置</el-button> -->
          <el-button
            type="primary"
            class="m-l-0 click-button"
            size="small"
            @click="search"
            icon="el-icon-search"
            :loading="dataLoading"
          >查询</el-button>
          <el-button
            :loading="dataLoading||downloadLoading"
            size="small"
            type="danger"
            icon="el-icon-download"
            @click="handleDownload"
          >导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="hover" class="ky-card ky-card-hdbg ky-mt10">
      <el-table
        ref="table"
        v-loading="dataLoading"
        size="medium"
        :data="tableData"
        show-summary
        :max-height="computedHeight"
        :summary-method="getSummaries"
        border
        :span-method="objectSpanMethod"
        :header-cell-style="{background:'#00c0ef', color:'#fff',fontWeight:'bold'}"
      >
        <el-table-column align="center" prop="DEP_AREA" label="院区"></el-table-column>
        <el-table-column align="center" prop="DEP" label="检查部门"></el-table-column>
        <el-table-column align="center" prop="SQDEP" label="申请科室"></el-table-column>
        <el-table-column align="center" prop="SL" label="实际预约数"></el-table-column>
        <el-table-column align="center" prop="BFB" label="部门预约占比(%)"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { dateFormatter } from '@/utils/validate'
import { getItemList, getDataForDepartment, getDepAreaList, getDepList, getModalityList, getCheckRoomList } from '@/api/api.js'
export default {
  name: 'TableApplyDep',
  mixins: [],
  data() {
    return {
      columnlist: [
        { name: '院区', value: 'DEP_AREA' },
        { name: '检查部门', value: 'DEP' }
      ],
      spanArr: {
        DEP_AREA: [],
        DEP: []
      }, // 数组合并span
      pos: {
        DEP_AREA: [],
        DEP: []
      },
      rules: {
        timeRange: { type: 'array', required: true, message: '请选择记录时间', trigger: 'change' }
      },
      formData: {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: [],
        timeRange: [dateFormatter(new Date(new Date() - 3600 * 1000 * 24 * 6), false), dateFormatter(new Date(), false)],
        depArea: [],
        modality: [],
        checkRoom: [],
        department: []
      },
      departmentOptions: [],
      depAreaOptions: [],
      scheduledDepOptions: [],
      modalityOptions: [],
      checkRoomOptions: [],
      dataLoading: false,
      downloadLoading: false,
      tableData: [],
      sumObj: {},
      // totalCount: 0,
      // pageSize: 10,
      // currentPage: 1,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {},
  computed: {
    computedHeight() {
      let height = window.innerHeight - 250
      return height
    }
  },
  created() { },
  async mounted() {
    this.$getHospitalList()
    this.formData.hospitalCode = this.$store.state.user.hospitalCode
    try {
      await this.getDepAreaOptions()
      this.getScheduledDepOptions()
      this.getDepartment()
      // this.getModalityOptions()
      // this.getCheckRoomOptions()
    } catch (err) {
      console.log(err)
    }
    this.search()
  },
  methods: {
    resetParam() {
      // 重置
      this.formData = {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: [],
        department: [],
        timeRange: [dateFormatter(new Date(new Date() - 3600 * 1000 * 24 * 6), false), dateFormatter(new Date(), false)],
        depArea: [],
        modality: [],
        checkRoom: []
      }
      //   this.search()
    },
    search() {
      // 查询
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.currentPage = 1
          this.fetchData()
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['院区', '检查部门', '申请科室', '实际预约数', '部门预约占比(%)']
        const filterVal = ['DEP_AREA', 'DEP', 'SQDEP', 'SL', 'BFB']
        const list = this.tableData
        this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data: this.excelData,
          filename: '申请科室统计列表',
          autoWidth: true
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      this.excelData = []
      jsonData.map((v, index) => {
        let tempArr = []
        filterVal.map(j => {
          if (v[j] || v[j] === 0) {
            if (j != 'children') {
              tempArr.push(v[j])
            } else {
              // 如果有children进行遍历
              this.formatJson(filterVal, v.children)
            }
          } else {
            tempArr.push('-')
          }
        })
        // console.log(tempArr)
        this.excelData.push(tempArr)
      })
    },
    // 计算合计数据
    setSumObj(data = []) {
      return new Promise(resolve => {
        this.sumObj = {}
        if (data) {
          for (let i = 0; i < data.length; i++) {
            const node = data[i]
            for (let k in node) {
              if (this.sumObj[k]) {
                this.sumObj[k] = this.sumObj[k] + node[k]
              } else {
                this.sumObj[k] = node[k]
              }
            }
          }
        }
        resolve()
      })
    },
    getSummaries(param) {
      const { columns, data } = param
      console.log(columns, data)
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property === 'BFB') {
          sums[index] = 100
          return
        }
        sums[index] = isNaN(this.sumObj[column.property]) ? '' : this.sumObj[column.property]
      })

      return sums
    },
    fetchData() {
      this.dataLoading = true
      let data = {
        hospitalCode: this.formData.hospitalCode,
        dateArr: this.formData.timeRange.join(','),
        depArea: this.formData.depArea.join(','),
        dep: this.formData.dep.join(','),
        sqDep: this.formData.department.join(',')
        // modality: this.formData.modality.join(','),
        // callRoom: this.formData.checkRoom.join(',')
      }
      getDataForDepartment(data).then(async res => {
        this.dataLoading = false
        if (!res) return
        console.log('res.Conten', res.Content)
        await this.setSumObj(res.Content)
        this.tableData = res.Content
        if (this.tableData.length > 0) {
          for (let i = 0; i < this.columnlist.length; i++) {
            this.getSpanArr(this.tableData, this.columnlist[i].value)
          }
        }
      }).catch(() => {
        this.dataLoading = false
      })
    },
    // 相同行的合并
    getSpanArr(data, column) {
      // 清空
      this.spanArr[column] = []
      this.pos[column] = []

      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr[column].push(1)
          this.pos[column] = 0
        } else {
          if (column === 'DEP_AREA') {
            if (data[i][column] === data[i - 1][column]) {
              this.spanArr[column][this.pos[column]] += 1
              this.spanArr[column].push(0)
            } else {
              this.spanArr[column].push(1)
              this.pos[column] = i
            }
          } else {
            if (data[i][column] === data[i - 1][column] && data[i].DEP_AREA === data[i - 1].DEP_AREA) {
              this.spanArr[column][this.pos[column]] += 1
              this.spanArr[column].push(0)
            } else {
              this.spanArr[column].push(1)
              this.pos[column] = i
            }
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex >= 0 && columnIndex <= 1) {
        const _row = this.spanArr[column.property][rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    getDepartment() {
      // 申请科室
      let data = {
        HospitalCode: this.formData.hospitalCode,
        type: '申请科室'
      }
      return new Promise(async resolve => {
        await getItemList(data).then(res => {
          if (res && res.code === 10000) {
            this.departmentOptions = res.content.list.map(_item => _item.item)
            resolve(res)
          }
        })
      })
    },
    getDepAreaOptions() {
      /* 影像区域列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode
      }
      return new Promise(async resolve => {
        await getDepAreaList(params).then((res) => {
          if (res.code === 10000) {
            this.depAreaOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea.join(',')
      }
      return new Promise(async resolve => {
        await getDepList(params).then((res) => {
          if (res.code === 10000) {
            this.scheduledDepOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getModalityOptions() {
      /* 检查设备列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea.join(','),
        dep: this.formData.dep.join(',')
      }
      return new Promise(async resolve => {
        await getModalityList(params).then((res) => {
          if (res.code === 10000) {
            this.modalityOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getCheckRoomOptions() {
      /* 检查机房列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea.join(','),
        dep: this.formData.dep.join(','),
        modality: this.formData.modality.join(',')
      }
      return new Promise(async resolve => {
        await getCheckRoomList(params).then((res) => {
          if (res.code === 10000) {
            this.checkRoomOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.depAreaOptions = []
          this.scheduledDepOptions = []
          this.departmentOptions = []
          this.formData.depArea = []
          this.formData.dep = []
          this.formData.department = []
          try {
            this.search()
            await this.getDepAreaOptions()
            this.getScheduledDepOptions()
            this.getDepartment()
          } catch (err) {
            console.log(err)
          }
          break
        case 'depArea':
          this.scheduledDepOptions = []
          this.formData.dep = []
          try {
            await this.getScheduledDepOptions()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    }
  },
  beforeDestroy() { },
  destroyed() { },
  beforeUpdate() { },
  updated() { }
}
</script>
<style lang='scss' scoped>
.ky-container {
  .param-type_input {
    /deep/ .el-input__inner {
      width: 180px;
    }
  }
  .content-title {
    margin-left: 4px;
    margin-bottom: 16px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }
}
>>> .el-table__footer-wrapper tbody td,
>>> .el-table__header-wrapper tbody td {
  background-color: #01c0ef;
  color: #fff;
}

>>> .el-table__fixed-footer-wrapper tbody td {
  // border-top: 1px solid #01c0ef;
  background-color: #01c0ef;
  color: #fff;
}
// .ky-form-inline-sm .el-form-item .el-date-editor--daterange.el-input__inner {
//   width: 456px;
// }
</style>

